package com.ziyia.a285;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    String[] strings = {"aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 搜索框
        SearchView searchView = findViewById(R.id.searchview);

        // 列表
        ListView listView = findViewById(R.id.list);

        listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, strings));
        // 启动过滤
        listView.setTextFilterEnabled(true);

        // 是否自动缩小图标
        searchView.setIconifiedByDefault(false);

        // 显示搜索按钮
        searchView.setSubmitButtonEnabled(true);

        // 提示文本
        searchView.setQueryHint("查找");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            // 单击搜索按钮时触发该方法
            @Override
            public boolean onQueryTextSubmit(String query) {
                Toast.makeText(MainActivity.this, query, Toast.LENGTH_SHORT).show();
                return false;
            }

            // 用户输入字符时触发该方法
            @Override
            public boolean onQueryTextChange(String newText) {
                if (TextUtils.isEmpty(newText)) {
                    listView.clearTextFilter();
                } else {
                    listView.setFilterText(newText);
                }
                return true;
            }
        });

    }
}